package com.wanlong.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wanlong.pojos.Bill;
import com.wanlong.service.BillService;


/**
 * @Package: com.ms.controller
 * @category：支付控制器
 * @author: Tom
 * @date: 2020年10月21日 下午7:05:21
 * @Company:
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/Alipay")
public class AlipayController {
	@Autowired 
	private BillService billService;

	@RequestMapping("/PayPage")
	public void payController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("---------------------------------------------------");
		// 获取初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				AlipayConfig.sign_type);
		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

		// 商户订单号，商户网站订单系统中唯一订单号，必填
		// String out_trade_no = request.getParameter("Order");
		// 付款金额，必填 ShopName
		// String total_amount = request.getParameter("Money");
		// 订单名称，必填
		// String subject = request.getParameter("Name");
		// 商品描述，可空
		// String body = "ssssss";

		String out_trade_no = new String(request.getParameter("Order").getBytes("ISO-8859-1"), "UTF-8");
		// 付款金额，必填
		String total_amount = new String(request.getParameter("Money").getBytes("ISO-8859-1"), "UTF-8");
		// 订单名称，必填
		String subject =request.getParameter("Name");
		// 商品描述，可空
		String body = request.getParameter("body");
		System.out.println(subject);

		// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
		
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求
		String url = "";
		try {
			url = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
			/*
			 * response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
			 * 
			 * response.getWriter().write(url); // 直接将完整的表单html输出到页面
			 * response.getWriter().flush(); response.getWriter().close();
			 */

		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
	
		 response.setContentType("text/html;charset=" + AlipayConfig.charset);
		 response.getWriter().write(url);// 直接将完整的表单html输出到页面
		 response.getWriter().flush();
		 response.getWriter().close();
	}

	/**
	 * 同步跳转
	 *
	 * @param request
	 * @throws Exception
	 */
	
	@RequestMapping("/returnUrl")
	public String returnUrl(HttpServletRequest request) throws Exception {
		System.out.println("----------------------------------");
		ModelAndView mav = new ModelAndView();

		// 获取支付宝GET过来反馈信息（官方固定代码）
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
				AlipayConfig.sign_type); // 调用SDK验证签名

		// 返回界面
		if (signVerified) {
			System.out.println("前往支付成功页面");
			mav.setViewName("gohome");
			return "gohome";
		} else {
			System.out.println("前往支付失败页面");
			mav.setViewName("error");
			return "error";
		}
		
	}

	/**
	 * 支付宝服务器异步通知
	 *
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/notifyUrl")
	public void notifyUrl(HttpServletRequest request) throws Exception {
		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
				AlipayConfig.sign_type); // 调用SDK验证签名
		System.out.println(signVerified);
		if (signVerified) { // 验证成功 更新订单信息
			System.out.println("异步通知成功");
			// 商户订单号
			String out_trade_no = request.getParameter("out_trade_no");
			// 交易状态
			String trade_status = request.getParameter("trade_status");
			System.out.println(trade_status);
			// 修改订单的支付状态为已付款
			
			billService.updateBillStatus(out_trade_no);	
		} else {
			System.out.println("异步通知失败");
		}

	}

}
